package com.eam.security.component;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.demo.exception.ApiException;
import com.eam.security.config.IgnoreUrlsConfig;
import com.eam.security.util.ConstantKey;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName: AccessFilter
 * @Description TODO
 * @Author: lingzhi
 * @Description:
 * @Date: Created in  2024/1/15  17:36
 */
@Component
public class AccessFilter extends BasicAuthenticationFilter {


    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    public AccessFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        String header = request.getHeader(ConstantKey.HEADER_KEY);

        FilterInvocation fi = new FilterInvocation(request, response, chain);
        //OPTIONS请求直接放行
        if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }

        String username = (String)request.getAttribute("username");
        if("root".equals(username)){
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }
        //白名单请求直接放行
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : ignoreUrlsConfig.getUrls()) {
            if(pathMatcher.match(path,request.getRequestURI())){
                fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
                return;
            }
        }

        // 如果token不为空，并且是以指定票据开头
/*        if (ObjectUtil.isNotEmpty(header) && header.startsWith(ConstantKey.BEARER)) {
            // 如果请求路径是放行路径，则直接跳过认证
            List<String> anonUrlList = ignoreUrlsConfig.getUrls();
            if (anonUrlList.contains(requestURI)) {
                chain.doFilter(request, response);
                return;
            }
        }*/

        String pathTwo = URLUtil.getPath(request.getRequestURI());
        String requestType = request.getMethod().toLowerCase(Locale.ROOT);
        String str = requestType + ":" + pathTwo.trim();
        // 权限角色   Authentication
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();

        
        if(authentication.getAuthorities().size()>0){
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (str.equals(grantedAuthority.getAuthority())) {
                    chain.doFilter(request, response);
                    return;
                }
            }

        }

        throw new AccessDeniedException("抱歉，您没有访问权限");
/*
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);*/
     //   chain.doFilter(request, response);
    }



}
